<template>
  <div class="w-full bg-[#fff]">
    <div class="w-full flex justify-between items-center">
      <div class="w-[44px] h-[44px] flex justify-center items-center">
        <van-uploader reupload :deletable="false" :after-read="afterRead" :max-count="1">
          <img class="w-[30px] h-[30px]" src="@/assets/images/send-img.png" />
        </van-uploader>
      </div>
      <div class="flex-1 w-0 flex items-center justify-center mr-[5px]">
        <van-field
          class="my-[6px] !bg-[#f5f5f5] rounded-[6px] !py-[6px]"
          autocomplete="new-password"
          v-model="state.content"
          clearable
          rows="1"
          autosize
          type="textarea"
          @focus="fieldFocus"
        />
      </div>
      <div class="mr-[5px] flex justify-center items-center">
        <img class="w-[30px] h-[30px]" src="@/assets/images/send-emoji.png" @click="handleEmoji" />
      </div>
      <div class="mr-[5px] flex justify-center items-center">
        <img class="w-[30px] h-[30px]" src="@/assets/images/send-quick.png" @click="handleReply" />
      </div>
      <div class="w-[44px] h-[44px] flex justify-center items-center">
        <img class="w-[30px] h-[30px]" src="@/assets/images/send-text.png" @click="send" />
      </div>
    </div>
    <div class="h-[230px] border-top" v-if="keyType != KeyType.input">
      <template v-if="keyType == KeyType.emoji">
        <EmojiCard @select="handleAddContent" />
      </template>
      <template v-if="keyType == KeyType.quick">
        <ReplyCard @select="handleAddContent" />
      </template>
    </div>
  </div>
</template>
<script lang="ts" setup>
import EmojiCard from "./emoji-card.vue";
import ReplyCard from "./reply-card.vue";

import { useUserStore } from "@/store/modules/user";
import { storeToRefs } from "pinia";
import { toast } from "@/utils/toast";
import { reqUploadImg } from "@/api/user";
import { debounce } from "lodash-es";
import { useKefuStore } from "@/store/modules/kefu";

enum ContentType {
  text = 22,
  image = 26
}
enum KeyType {
  input = 1,
  emoji = 2,
  quick = 3
}
const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
const state = inject<CustomerState>("state") as CustomerState;
const contentId = inject("contentId") as string;
const userStore = useUserStore();
const { chatToken } = storeToRefs(userStore);
const kefu = useKefuStore();
const emit = defineEmits(["scrollToBottom"]);
const keyType = ref(KeyType.input);

const send = debounce(() => {
  if (!state.content) {
    return toast.info("请输入内容");
  }
  pushMessage(state.content);
  state.content = "";
}, 500);

// push 消息
const pushMessage = (content: string, msg_type = ContentType.text) => {
  const params = {
    token: chatToken.value, // 替换为实际用户的token
    roomName: contentId,
    content,
    msgType: msg_type,
    sendType: "private" // 房间类型 (如需私聊，可设置为 PRIVATE)
  };
  kefu.client?.emit("send_msg", params);
};

// 上传图片并发送图片消息
const afterRead: any = async (file: any) => {
  console.log("afterRead", file);
  const isIMAGE = file.file.type === "image/jpeg" || "image/jpg" || "image/png";
  const isLt200K = file.file.size / 1024 < 200;

  if (!isIMAGE) {
    return toast.fail("上传文件只能是图片格式!");
  }
  if (!isLt200K) {
    return toast.fail("发送图片大小不能超过 200KB!");
  }
  const loading = toast.loading("上传中...");
  try {
    let param = new FormData();
    param.append("ImgPath", file.file);
    let res = await reqUploadImg(param);
    pushMessage(res.data.ImgPath, ContentType.image);
    file.status = "done";
    loading.close();
  } catch (error) {
    loading.close();
    file.status = "failed";
    console.log(error);
  }
};

const fieldFocus = () => {
  keyType.value = KeyType.input;
  if (state.content) {
    state.content = state.content + " ";
  } else {
    state.content = " ";
  }
  nextTick(() => {
    setTimeout(() => {
      document.documentElement.scrollTop = isSafari ? 318 : document.documentElement.scrollHeight;
      state.content = state.content.trim();
    }, 200);
  });
};

const handleEmoji = () => {
  if (keyType.value != KeyType.emoji) {
    keyType.value = KeyType.emoji;
  } else {
    keyType.value = KeyType.input;
  }
};

const handleReply = () => {
  if (keyType.value != KeyType.quick) {
    keyType.value = KeyType.quick;
  } else {
    keyType.value = KeyType.input;
  }
};

const handleAddContent = (e: any) => {
  state.content += e;
};

watch(
  () => state.content,
  () => {
    emit("scrollToBottom");
  }
);

watch(
  () => keyType.value,
  () => {
    emit("scrollToBottom");
  }
);

defineExpose({
  shrink() {
    keyType.value = KeyType.input;
    emit("scrollToBottom");
  }
});
</script>
<style scoped>
.game-footer-safe {
  @apply border-b-[20px] border-solid border-[#fff];
}
</style>
<style lang="scss" scoped>
.van-field {
  background-color: transparent;
  padding: 0 10px;
  width: 100%;
  height: 100%;
  border-radius: 6px;
  display: flex;
  align-items: center;
  font-size: 16px;
  :deep(.van-field__control) {
    height: 34px;
  }
}
</style>
